package com.jdl.iscm.replenish;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.xml.XmlTest;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @Author: Ran
 * @Date: 2021/8/31
 **/
public class BaseProvider {

    /**
     * 根据testng.xml中配置的parameter反射设置每个测试类的data provider
     *
     * @param context
     * @return
     * @throws Exception
     */
    @DataProvider(name = "data")
    public static Object[][] getSetting(ITestContext context) throws Exception {
        XmlTest xmlTest = context.getCurrentXmlTest();
        Class listenerClz = Class.forName(xmlTest.getParameter("listener"));
        Class sheetClz = Class.forName(xmlTest.getParameter("sheetExcel"));
        ReadListener readListener = (ReadListener) listenerClz.newInstance();

        ReadSheet sheet = EasyExcel.readSheet(xmlTest.getParameter("sheetName")).head(sheetClz).headRowNumber(1).registerReadListener(readListener).build();
        EasyExcel.read(new BufferedInputStream(new FileInputStream(xmlTest.getParameter("excel-path")))).build().read(sheet);
        //因为各实现的listener中就定义了一个字段所以直接用
        Field field = readListener.getClass().getDeclaredFields()[0];
        field.setAccessible(true);
        List list = (List) field.get(readListener);
        Object[][] objects = new Object[list.size()][1];
        IntStream.range(0, list.size()).forEach(i -> objects[i][0] = list.get(i));
        return objects;
    }
}
